package com.truckdispatching.http.base;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import com.truckdispatching.http.base.HttpTask.RequestType;

public abstract class HttpController implements HttpTaskListener {

	protected HttpTask mHttpTask;

	public abstract String getRequestUrl();

	public HttpTask sendRequest(HashMap<String, String> params, boolean isPost) {
		if (isPost) {
			byte[] requestData = null;
			if (params != null && params.size() > 0) {
				StringBuffer sb = new StringBuffer();
				for (java.util.Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null && !value.equals("")) {
						sb.append("&");
						sb.append(entry.getKey());
						sb.append("=");
						sb.append(value);
					}
				}
				try {
					requestData = sb.toString().getBytes("UTF-8");
				} catch (UnsupportedEncodingException e) {
				}
			}
			mHttpTask = new HttpTask(getRequestUrl(), requestData, this);
			mHttpTask.setRequestType(RequestType.POST);
		} else {
			StringBuffer sb = new StringBuffer();
			int i = 0;
			if (params != null && params.size() > 0) {
				for (java.util.Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					String key = entry.getKey();
					if (key != null && !key.equals("") && value != null && !value.equals("")) {
						if (i == 0) {
							sb.append("?");
						} else {
							sb.append("&");
						}
						sb.append(key);
						sb.append("=");
						sb.append(value);
						i++;
					}
				}
			}
			mHttpTask = new HttpTask(getRequestUrl() + sb.toString(), null, this);
			mHttpTask.setRequestType(RequestType.GET);
		}
		HttpManager.getInstance().sendHttpTask(mHttpTask);
		return mHttpTask;
	}

	public HttpTask sendGetRequest(HashMap<String, String> params) {
		StringBuilder sb = new StringBuilder(getRequestUrl());
		if (params != null && params.size() > 0) {
			int i = 0;
			for (java.util.Map.Entry<String, String> entry : params.entrySet()) {
				String value = entry.getValue();
				if (value != null && !value.equals("")) {
					if (i == 0) {
						sb.append("?");
					} else {
						sb.append("&");
					}
					sb.append(entry.getKey());
					sb.append("=");
					sb.append(value);
					i++;
				}
			}
		}
		mHttpTask = new HttpTask(sb.toString(), null, this);
		mHttpTask.setRequestType(RequestType.GET);
		HttpManager.getInstance().sendHttpTask(mHttpTask);
		return mHttpTask;
	}

	public void cancelHttpRequest() {
		if (mHttpTask != null) {
			mHttpTask.cancel();
		}
	}
}
